package ele_handler

import "go-yuque/yuque/extend"

func init() {
	registerInitFunc(
		func() YuqueElementHandler {
			h := &aHandlerStruct{}
			h.elements = []string{"a"}
			h.attributes = map[string]string{"href": ""}
			return h
		})
}

type aHandlerStruct struct {
	BaseHandler
	extend.BufferStruct
}

func (a *aHandlerStruct) preHandle() (err error) {
	// 注入 a 标记
	a.ctxMap["wrapA"] = true
	// 切换缓冲区
	a.ChangeToBuffer(a.textContentP)
	return
}

func (a *aHandlerStruct) doHandle() (err error) {
	return
}

func (a *aHandlerStruct) postHandle() (err error) {
	defer delete(a.ctxMap, "wrapA")
	// 恢复缓冲区
	defer a.RecoverFromBuffer(a.textContentP)

	// 获取 a 标签 href 属性值
	hrefVal := findAttribute(a.node, "href")
	// MD文档的a标签格式: [text](href)
	a.WriteInBuffer("[" + a.GetTextContext() + "](" + hrefVal + ")")

	return
}
